<?php

/** Copyright 2014 TinPhp Systems, Inc.
 * @package TinPhp
 * @author zhangxilian 2013-8-22
 */
require_once (TIN_APP_PATH . "configs/log.conf.php");

/**
 * 日志操作类
 */
class TinLogger {
    /** 设置日志产生的类名 */
    public $className = 'unset';
    var $g_log_file_path = "/logs/sys.log";
    var $g_log_file = "/logs/sys.log";    

    /** 初始化日志类
     * @param string $logfile 日志文件路径，必须包含有.如：/logs/log.txt
     * @param string $claName 产生日志的对象名称 */
    public function __construct($logfile, $claName = "unset") {
        $this->g_log_file_path = $logfile;
        $this->setLogFile('info');
        $this->className = $claName;
    }
     /** 自定义类型日志，write_log外部调用
     * @param string message 日志内容
     * @param string $type 日志文件后缀 */
    public function custom($message, $type){
        if (LOG_CUSTOM_ISOPEN) {
            $this->write_log($message, $type);
        }
    }
    /** 一般日志
     * @param string $message 日志内容 */
    public function info($message) {
        if (LOG_INFO_ISOPEN) {
            $this->write_log($message, 'info');
        }
    }

    /** 错误日志
     * @param string $message 日志内容 */
    public function error($message) {
        if (LOG_ERROR_ISOPEN) {
            $this->write_log($message, 'error');
        }
    }

    /** 调试日志
     * @param string $message 日志内容 */
    public function debug($message) {
        if (LOG_DEBUG_ISOPEN) {
            $this->write_log($message, 'debug');
        }
    }
    /** 设置日志文件
     * @param string $type 日志文件后缀 sys.dubug.2014-06-25.log */
    private function setLogFile($type){
        $ext = explode(".", $this->g_log_file_path);
        if(PATH_SEPARATOR==':'){    //Linux
            $this->g_log_file = $ext[0] . ".".$type."." . date("Y-m-d") . "." . $ext[1];
        }else{
            $this->g_log_file = ".".$ext[0] . ".".$type."." . date("Y-m-d") . "." . $ext[1];
        }
        
    }
    /** 写入日志文件 
     * @param string message 日志内容
     * @param string $type 日志文件后缀 */
    private function write_log($message, $type) {
        if (LOG_ALL_ISOPEN) {
            $this->setLogFile($type);
            if ((strcmp($this->g_log_file, "") == 0) || (strcmp($this->g_log_file, "logfile") == 0)) {
                echo "[" . $this->className . "]" . $message;
            } else {
                $fp = @fopen($this->g_log_file, "a+");
                if (flock($fp, LOCK_EX)) {
                    @fwrite($fp, date("Y-m-d H:i:s") . "[" . $this->className . "]:[".$_SERVER['REQUEST_URI']."] \n $message\n");
                    @flock($fp, LOCK_UN);
                } else {
                    echo "Couldn't lock the file !";
                }
                @fclose($fp);
            }
        }
    }
    
    /** 关闭当前日志文件 */
    private function log_reset() {
        @unlink($this->g_log_file);
    }
    
    function __destruct() {
        //print("bye bye");
        //$this->log_reset();
    }

}

?>
